package com.fu.shop.service.Impl;

import com.fu.core.common.BusinessException;
import com.fu.core.common.ExceptionCode;
import com.fu.core.pojo.Banner;
import com.fu.core.pojo.Notices;
import com.fu.core.pojo.Shop;
import com.fu.core.pojo.SystemNotices;
import com.fu.core.service.impl.BaseServiceImpl;
import com.fu.core.util.JsonUtil;
import com.fu.core.util.ThreadLocalUtil;
import com.fu.shop.mapper.NoticesMapper;
import com.fu.shop.mapper.ShopMapper;
import com.fu.shop.mapper.SystemNoticesMapper;
import com.fu.shop.mapper.UserNoticesMapper;
import com.fu.shop.service.ShopService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 付龙江
 * @date 2022/2/5 11:31
 */
@Service("shopService")
@Transactional(rollbackFor = Throwable.class)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {

    private final static String INDEX_BANNER = "indexBanner";

    ShopMapper shopMapper;
    NoticesMapper noticesMapper;
    UserNoticesMapper userNoticesMapper;
    RedisTemplate<String,Object> redisTemplate;
    ValueOperations<String,Object> stringOps;
    ListOperations<String,Object> listOps;
    static Map<String,Object> map;
    SystemNoticesMapper systemNoticesMapper;
    @Autowired(required = false)
    public ShopServiceImpl(ShopMapper shopMapper, NoticesMapper noticesMapper,
                           UserNoticesMapper userNoticesMapper,
                           RedisTemplate<String, Object> redisTemplate,
                           SystemNoticesMapper systemNoticesMapper) {
        this.shopMapper = shopMapper;
        this.noticesMapper = noticesMapper;
        this.userNoticesMapper = userNoticesMapper;
        this.redisTemplate = redisTemplate;
        stringOps = redisTemplate.opsForValue();
        listOps = redisTemplate.opsForList();
        this.systemNoticesMapper = systemNoticesMapper;
    }

    private static void getThreadMessage(){
        Object object = ThreadLocalUtil.getObject();
        System.out.println(object);
        map = JsonUtil.stringToObject(object.toString(), Map.class);
        System.out.println(map);
    }

    @Override
    public Shop selectShop() throws Exception {
        //拿到线程中的信息
        getThreadMessage();
        Object o = map.get("shopId");
        if (StringUtils.isEmpty(o)){
            throw new BusinessException(ExceptionCode.NO_MATCHING_RESULT);
        }
        Integer shopId = Integer.valueOf(o.toString());
        //利用tk查到对应的信息 并返回
        return shopMapper.selectByPrimaryKey(shopId);
    }

    /**
     * 更新店铺基本信息
     *
     * @param shop 店铺信息
     * @return 返回更新后的信息
     * @throws Exception 异常处理
     */
    @Override
    public Shop updateShop(Shop shop) throws Exception {
        //拿到线程中的信息
        getThreadMessage();
        Object o = map.get("shopId");
        if (StringUtils.isEmpty(o)){
            throw new BusinessException(ExceptionCode.NO_MATCHING_RESULT);
        }
        Integer shopId = Integer.valueOf(o.toString());
        shop.setShopId(shopId);
        Shop shop1 = shopMapper.selectByPrimaryKey(shopId);
        //如果没有修改任何信息  就返回原来的信息
        if (shop1.equals(shop)){
            return shop;
        }
        //不一样就直接修改
        Integer save = save(shop);
        if (save!=1){
            throw new BusinessException(ExceptionCode.UPDATE_FAILED);
        }
        return shop;
    }

    /**
     * banner信息
     *
     * @param list 存放banner的集合
     * @return 返回banner集合
     * @throws Exception 异常处理
     */
    @Override
    public List<Banner> bannerMessage(List<Banner> list) throws Exception {
        List<Banner> banners = new ArrayList<>();
        //第一次打开店铺banner做查询工作
        if (list == null || list.size()<1){
            List<Object> objectList = listOps.range(INDEX_BANNER, 0, -1);
            if (objectList == null || objectList.size() < 1){
                throw new BusinessException(ExceptionCode.NO_BANNERS);
            }
            for (Object o : objectList) {
                banners.add(JsonUtil.stringToObject(JsonUtil.objectToString(o),Banner.class));
            }
            return banners;
        }
        //如果list不为null  证明已经被修改过了
        //直接删除原来redis中中所有数据，然后再将数据从左向右依次导入
        if (redisTemplate.hasKey(INDEX_BANNER)){
            redisTemplate.delete(INDEX_BANNER);
        }
        for (Banner banner : list) {
            listOps.rightPush(INDEX_BANNER,banner);
        }
        return list;
    }

    /**
     * 查询系统通知
     * @param page 页码
     * @param size 长度
     * @return 返回逆序
     */
    @Override
    public PageInfo<SystemNotices> selectSystemNotices(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Condition condition = new Condition(SystemNotices.class);
        condition.orderBy("systemId").desc();
        List<SystemNotices> systemNotices = systemNoticesMapper.selectByExample(condition);
        return PageInfo.of(systemNotices);
    }

    /**
     * 删除历史通知
     *
     * @param systemId 通知编号
     * @return 返回执行成功的行数
     */
    @Override
    public void deleteSystemNotices(Integer systemId) throws Exception {
        int i = systemNoticesMapper.deleteByPrimaryKey(systemId);
        if (i!=1){
            throw new BusinessException(ExceptionCode.DELETE_FAILED);
        }
    }

    /**
     * 发布通知
     *
     * @param title   通知标题
     * @param notices 通知内容
     * @throws Exception 异常处理
     */
    @Override
    public void addSystemNotice(String title, String notices) throws Exception {
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(notices)){
            throw new BusinessException(ExceptionCode.PARAMETER_PASSING_EXCEPTION);
        }
        SystemNotices systemNotices = new SystemNotices();
        systemNotices.setSystemText(notices);
        systemNotices.setSystemTitle(title);
        systemNotices.setSystemTime(new Timestamp(System.currentTimeMillis()));
        int i = systemNoticesMapper.insertSelective(systemNotices);
        if (i!=1){
            throw new BusinessException(ExceptionCode.INSERT_FAILED);
        }
    }

    /**
     * 查询用户最新消息
     *
     * @param status 消息状态
     * @param name   姓名模糊查询
     * @param page   页码
     * @param size   每页条数
     * @return 返回对应结果
     */
    @Override
    public PageInfo<Map<String, Object>> selectUserNotices(Integer status, String name, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<Map<String, Object>> list = userNoticesMapper.selectUserNotices(status, name);
        return PageInfo.of(list);
    }

    /**
     * 某个用户的详情信息
     *
     * @param userId 用户id
     * @param page   页码
     * @param size   每页条数
     * @return 返回消息集合
     */
    @Override
    public PageInfo<Notices> selectUserNoticesDetails(Integer userId, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<Notices> notices = userNoticesMapper.selectUserNoticesDetails(userId);
        return PageInfo.of(notices);
    }

    /**
     * 回复消息
     *
     * @param userId  用户编号
     * @param notices 回复的内容
     * @throws Exception 异常处理
     */
    @Override
    public void replayNotices(Integer userId, String notices) throws Exception {
        if (userId == null || StringUtils.isEmpty(notices)){
            throw new BusinessException(ExceptionCode.PARAMETER_PASSING_EXCEPTION);
        }
        List<Notices> list = userNoticesMapper.selectUserNoticesDetails(userId);
        if (list == null || list.size() < 1){
            throw new BusinessException(ExceptionCode.NO_NOTICES);
        }
        Notices notices1 = list.get(0);
        notices1.setNoticesReplyTime(new Timestamp(System.currentTimeMillis()));
        notices1.setNoticesReplyMessages(notices);
        //保存回复的消息
        noticesMapper.updateByPrimaryKeySelective(notices1);
        //修改回复的状态
        userNoticesMapper.updateStatus(userId);
    }
}
